package demo.service.impl;

import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import demo.vo.common.CachedObject;
import demo.service.CacheService;

//@Service
public class RedisCacheService implements CacheService {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private ValueOperations<String, Object> valueOperations;

    public RedisCacheService(RedisTemplate<String, Object> redisTemplate) {
        if (redisTemplate == null) {
            throw new IllegalArgumentException("redisTemplate is null");
        }
        this.valueOperations = redisTemplate.opsForValue();
    }

    @Override
    public void set(String key, Object value, long seconds) {
        try {
            valueOperations.set(key, new CachedObject(value), seconds, TimeUnit.SECONDS);
        } catch (Exception e) {
            logger.error("", e);
        }
    }

    @Override
    public CachedObject get(String key) {
        try {
            CachedObject cachedObject = (CachedObject) valueOperations.get(key);
            if (cachedObject == null) {
                return null;
            }
            return cachedObject;
        } catch (Exception e) {
            logger.error("", e);
            return null;
        }
    }

}
